package ch.usi.inf.pf2.spreadsheet;

/**
 * @author Ehsanvala.uk@gmail.com
*/

import java.io.IOException;
import java.lang.String;


import ch.usi.inf.pf2.CSV.FileRead;
import ch.usi.inf.pf2.CSV.FileWrite;
import ch.usi.inf.pf2.CSV.Message;
import ch.usi.inf.pf2.cell.Cell;
import ch.usi.inf.pf2.cell.CellArray;

public class SpreadSheetCellArray implements CellArray {		
	private int ROW_COUNT ;
	private int COLUMN_COUNT;
	private Cell [][] sparseMatrix;
	
	public SpreadSheetCellArray(int rows, int columns) {
		this.ROW_COUNT=rows;
		this.COLUMN_COUNT=columns;
		this.sparseMatrix=new Cell [rows][columns];
	}
	
	public int getRowCount() {
		return ROW_COUNT;
	}
	
	public int getColumnCount() {
		return COLUMN_COUNT;
	}

	public void setValueAt(String val, int row, int column) {
		if(row > ROW_COUNT || column > COLUMN_COUNT) { 
			System.out.println("You are out of spreadsheet"); 
		} else {
			if (sparseMatrix[row][column] != null) {
				sparseMatrix[row][column].setStr(val);
			} else {
				sparseMatrix[row][column] = new Cell(val,this);
			}
		}
	}

	public String getValue(int row ,int column) {
		if (row > ROW_COUNT || column > COLUMN_COUNT) {
			return "You are out of spreadsheet";
		} else {
			if (sparseMatrix[row][column] != null) {
				return(Double.toString(sparseMatrix[row][column].evaluate().get()));
			} else {
				return("");
			}
		}
	}

	public void print() {
		for(int i=0; i<ROW_COUNT ;i++) {
			for(int j=0; j<COLUMN_COUNT; j++) {
				if(sparseMatrix[i][j]== null) {
					System.out.print("\t"+"\t");
				} else {
					System.out.print("\t" + sparseMatrix[i][j].evaluate().get());
				}
			}
			System.out.println();
		}
	}

	public Cell getCell(int row, int column) {
		if (row > ROW_COUNT || column > COLUMN_COUNT) {
			return null;
		} else {
			return sparseMatrix[row][column];
		}
	}
	
	public static void main(String[] args) {
		SpreadSheetCellArray test = new SpreadSheetCellArray (30,30);
		test.setValueAt("=-200", 27,27);
		test.setValueAt("=(2+8)/5", 28, 28);
		test.setValueAt("=AA28+AB29", 3, 3);
		test.setValueAt("1", 4,4);
		test.print();
		SpreadSheetCellArray spread = FileRead.readCSV("/Users/ehsan/Desktop/PF2Project/SpreadSheet/src/ch/usi/inf/pf2/spreadsheet/Mona.csv");
//		spread.print();
		if (FileWrite.writeFile(spread, "/Users/ehsan/Desktop/copy.csv") == Message.SUCCESS) {
			System.out.println("Wrote successfully into the file");
		} else {
			System.out.println("There was an error while trying to write the file");
		}
	}
}